package com.it.selfAfter.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.selfAfter.dto.ProductBaseDTO;
import com.it.selfAfter.dto.ProductionDTO;
import com.it.selfAfter.entity.Production;
import com.it.selfAfter.entity.ProductionType;
import com.it.selfAfter.mapper.ProductMapper;
import com.it.selfAfter.service.ProductService;
import com.it.selfAfter.service.UserService;
import com.it.selfAfter.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@Slf4j
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Production> implements ProductService {
    @Autowired
    private UserService userService;

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductMapper productMapper;


    /**
     * @作者: Coke
     * @注释: 保存商品信息
     * @DateTime: 2023/5/25 20:59
     *
     * @param name:
     * @param description:
     * @param phone:
     * @param imgs:
     * @return Product
     */
    @Override
    public Production saveProduct (String name, String productionType, String result, String address,
                                   String description, String phone, String userId, String createName, MultipartFile[] imgs) {

        File file = null;
        Production production = new Production();
        try {
            production.setName(name);
            production.setProduction_type(productionType);
            production.setArea(result);
            production.setAddress(address);
            production.setDescription(description);
            production.setPhone(phone);
            production.setUser_id(userId);
            production.setCreate_user(createName);
            Date createTime = new Date();
            StringBuilder keys = new StringBuilder();

            boolean flag = true;
            if (!Objects.isNull(imgs)) {
                for (MultipartFile img : imgs) {
                    if (!img.isEmpty()) {
                        // 调用接口上传照片
                        String imgKey = userService.uploadImg(img, Long.valueOf(phone));
                        if (! Objects.isNull(result)){
                            if (flag){
                                keys.append(imgKey);
                                flag = false;
                            }else {
                                keys.append(",").append(imgKey);
                            }
                        }
                    }
                }
            }
            production.setImgs(keys.toString());
            // 保存商品基本数据
            productMapper.saveProduct(name, productionType, result, address, description, phone, userId,
                    createName,keys.toString(), createTime);
        } catch (Exception e) {
            log.error("文件上传失败:{}", e.getMessage());
            return null;
        } finally {
            if (! Objects.isNull(file)) {
                file.delete();
            }
        }
        return production;
    }

    /**
     * @作者: Coke
     * @注释: 根据查询条件分页查询作品信息
     * @DateTime: 2023/5/28 21:53
     *
     * @param query: 查询条件
     * @param size:每页大小
     * @param page:  第几页
     * @return Result<?>
     */
    @Override
    public Result<?> queryProductList (Map<String, String> query, Integer size, Integer page) {
        String min_date = query.get("min_date"); // 最小时间
        String max_date = query.get("max_date"); // 最大时间
        String area = query.get("area"); // 区域
        String pType = query.get("p_type"); // 作品类型
        String name = query.get("name"); // 作品名称
        Integer startIndex = (page -1) * size;
        List<ProductionDTO> pageMap = productMapper.queryProductList(min_date, max_date, area, pType, name, size, startIndex);
        log.warn(pageMap.toString());
        return Result.success(pageMap);
    }

    /**
     * @Author: CaoYouGen
     * @注释: 根据作品id获取商品详情信息
     * @DateTime: 2023/5/30 9:56
     *
     * @param id:
     * @return ProductionDTO
     */
    @Override
    public ProductionDTO getProductInfoById(Long id,String userId) {
        Map<String, Object> proMap = productMapper.getProductInfoById(id, userId);
        ProductionDTO productionDTO = new ProductionDTO();
        productionDTO.setName(String.valueOf(proMap.get("name")));  // 商品名称
        productionDTO.setProduction_type(String.valueOf(proMap.get("production_type")));  // 商品类型
        String user_name = String.valueOf(proMap.get("user_name"));  // 员工名称
        String nick_name = String.valueOf(proMap.get("nick_name")); // 昵称
        if ("".equals(user_name) || user_name == null || "null".equals(user_name)){
            productionDTO.setCreate_user(nick_name);  // 创建用户
        }else {
            productionDTO.setCreate_user(user_name);  // 创建用户
        }
        productionDTO.setArea(String.valueOf(proMap.get("area")));  // 地点
        productionDTO.setPhone(String.valueOf(proMap.get("phone")));  // 联系方式
        productionDTO.setStatus(String.valueOf(proMap.get("status"))); // 作品状态
        productionDTO.setUserId(String.valueOf(proMap.get("user_id"))); // user_id
        productionDTO.setHeadimgurl(String.valueOf(proMap.get("headimgurl"))); // 头像
        productionDTO.setAddress(String.valueOf(proMap.get("address"))); // 详细地址

        String dateString = String.valueOf(proMap.get("create_time")); // 创建（发布）时间
        if (dateString != null && !dateString.isEmpty() && !dateString.equals("null")) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
            try {
                Date date = formatter.parse(dateString);
                productionDTO.setCreate_time(date);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        productionDTO.setDescription(String.valueOf(proMap.get("description")));  // 物品描述
        productionDTO.setImgs(String.valueOf(proMap.get("imgs")));  // 作品图片
        String collect = String.valueOf(proMap.get("collect"));
        if ("null".equals(collect)) {
            productionDTO.setCollect("0");  // 没有收藏
        } else {
            productionDTO.setCollect("1");  // 有收藏
        }
        return productionDTO;
    }

    /**
     * @Author: CaoYouGen
     * @注释: 获取 地区 作品类型
     * @DateTime: 2023/5/30 14:09
     *
     * @return ProductBaseDTO
     */
    @Override
    public ProductBaseDTO getProductBaseInfo() {
        List<String> baseInfo = productMapper.getProductBaseInfo();

        ProductBaseDTO productBaseDTO = new ProductBaseDTO();
        // 将 List<String> 转换为 String[]
        String[] baseInfoArray = baseInfo.toArray(new String[0]);
        if (baseInfo != null && !baseInfo.isEmpty()) {
            productBaseDTO.setPTypes(baseInfoArray);
        }
        return productBaseDTO;
    }

    /**
     * @Author: CaoYouGen
     * @注释: 删除收藏信息
     * @DateTime: 2023/5/30 16:28
     *
     * @param proId:
     * @return String
     */
    @Override
    public String updateCollectById(String proId,String phone,String userId) {
        int i = productMapper.updateCollectById(proId,userId);
        return i > 0 ? "修改成功" : "修改失败";
    }

    /**
     * @Author: CaoYouGen
     * @注释: 添加收藏信息
     * @DateTime: 2023/5/30 16:28
     *
     * @param proId:
     * @return String
     */
    @Override
    public String saveCollectById(String proId,String phone,String userId) {
        int i = productMapper.saveCollectById(phone, proId, userId);
        return i > 0 ? "修改成功" : "修改失败";
    }

    /**
     * @Author: CaoYouGen
     * @注释: 回显数据
     * @DateTime: 2023/5/31 13:52
     *
     * @param proId:
     * @param phone:
     * @param userId:
     * @return ProductionDTO
     */
    @Override
    public ProductionDTO echoProductInfoById(String proId, String phone, String userId) {
        return productMapper.echoProductInfoById(proId);
    }

    /**
     * @Author: CaoYouGen
     * @注释: 修改 作品
     * @DateTime: 2023/5/31 14:58
     *
     * @param proId: 作品id
     * @param name:  作品名称
     * @param productionType: 作品类型
     * @param result: 区域
     * @param address: 详细地址
     * @param description: 作品介绍
     * @param deleteImgs: 需要删除的图片
     * @param noDeleteImg: 不需要删除的图片
     * @param imgs:  新上传的图片
     * @return Production
     */
    @Override
    public Production updateProduct(String proId, String name, String productionType, String result, String address,
                                    String description, String deleteImgs, String noDeleteImg, MultipartFile[] imgs) {
        File file = null;
        File tempFile = null;
        File resizedFile = null;
        ProductionDTO ProductionDTO = new ProductionDTO();
        try {
            StringBuilder keys = new StringBuilder();
            boolean flag = true;
            // 拼接上不需要删除的key
            if (!Objects.isNull(noDeleteImg)) {
                keys.append(noDeleteImg);
            }
 /*           if (!Objects.isNull(imgs)) {
                if (!Objects.isNull(noDeleteImg) && noDeleteImg.length() != 0) {
                    keys.append(",");
                }
                for (MultipartFile img : imgs) {
                    if (!img.isEmpty()) {
                        // 调用接口上传照片
                        String imgKey = userService.uploadImg(img, Long.valueOf(phone));
                        if (! Objects.isNull(result)){
                            if (flag){
                                keys.append(imgKey);
                                flag = false;
                            }else {
                                keys.append(",").append(imgKey);
                            }
                        }

                        String type = img.getContentType().split("/")[1];
                        // 调用接口上传照片
                        String originalFilename = img.getOriginalFilename();
                        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                        file = File.createTempFile("temp", suffix);
                        try (OutputStream outputStream = new FileOutputStream(file)) {
                            outputStream.write(img.getBytes());
                        }
                        // 调用接口上传照片
                        String key = UUID.randomUUID() + "_type=" + type;
//                            File png = imageResize(file,  type);
                        fileService.upload(file, key);
                        keys = flag ? keys.append(key) : keys.append(",").append(key);
                        flag = false;
                    }
                }
            }
            // 保存商品基本数据
            Product save = productMapper.save(product);
            // 修改商品图片
            int i = ProductionDTO.updateImg(proId, keys.toString());
            BeanUtils.copyProperties(product, ProductionDTO);
            ProductionDTO.setImg_key(keys.toString());
            // 删除 不需要的图片
            String[] deleteImgArr = objectToArray(deleteImgs);
            for (int j = 0; j < deleteImgArr.length; j++) {
                String s = deleteImgArr[j];
                fileService.delete(s);
            }*/

        }catch (Exception e) {
            log.error("文件上传或删除失败:{}", e.getMessage());
            return null;
        } finally {
            if (!Objects.isNull(file)) {
                file.delete();
            }
            if (!Objects.isNull(resizedFile)) {
                resizedFile.delete();
            }
        }
        return null;
    }

    /**
     * @作者: Coke
     * @注释: 获取初始信息（作品的类型等）
     * @DateTime: 2023/5/28 10:59
     *
     * @return ProductionType
     */
    @Override
    public List<ProductionType> getProInfo () {
        List<ProductionType> proInfo = productMapper.getProInfo();
        log.info(proInfo.toString());
        return productMapper.getProInfo();
    }

    // 按照逗号分隔 为数组
    public String[] objectToArray(Object labelsObj) {
        String str = labelsObj.toString();
        return str.split(",");
    }
}
